<template>
  <div class="schedule-management">
    <div class="page-header">
      <h2>排课管理</h2>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="学期">
          <el-select 
            v-model="searchForm.semester" 
            placeholder="学期" 
            clearable 
            style="width: 140px"
          >
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2025秋季" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="课程名称">
          <el-input 
            v-model="searchForm.courseName" 
            placeholder="支持模糊搜索" 
            clearable 
            style="width: 180px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Reading /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="教师姓名">
          <el-input 
            v-model="searchForm.teacherName" 
            placeholder="支持模糊搜索" 
            clearable 
            style="width: 160px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="班级名称">
          <el-input 
            v-model="searchForm.clazzName" 
            placeholder="支持模糊搜索" 
            clearable 
            style="width: 160px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><School /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="排课类型">
          <el-select 
            v-model="searchForm.scheduleType" 
            placeholder="类型" 
            clearable 
            style="width: 120px"
          >
            <el-option label="正常" value="正常" />
            <el-option label="调课" value="调课" />
            <el-option label="补课" value="补课" />
            <el-option label="考试" value="考试" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="状态" 
            clearable 
            style="width: 120px"
          >
            <el-option label="有效" value="ACTIVE" />
            <el-option label="取消" value="CANCELLED" />
            <el-option label="暂停" value="SUSPENDED" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
          <el-button type="success" @click="handleExportSchedule" :icon="Download">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleIntelligentSchedule">
          <el-icon><Star /></el-icon>智能排课
        </el-button>
        <el-button type="success" @click="handleAdd">
          <el-icon><Plus /></el-icon>手动排课
        </el-button>
        <el-button type="warning" @click="handleBatchAdjust">
          <el-icon><Edit /></el-icon>批量调整
        </el-button>
        <el-button type="info" @click="handleConflictCheck">
          <el-icon><Warning /></el-icon>冲突检查
        </el-button>
        <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table 
        :data="scheduleList" 
        v-loading="loading" 
        stripe 
        border 
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="courseName" label="课程名称" width="150" />
        <el-table-column prop="teacherName" label="教师" width="120" />
        <el-table-column prop="clazzName" label="班级" width="120" />
        <el-table-column prop="classroomName" label="教室" width="120" />
        <el-table-column label="时间安排" width="200">
          <template #default="scope">
            <div class="time-info">
              <div>第{{ scope.row.weekNo }}周</div>
              <div>{{ getWeekDayName(scope.row.dayOfWeek) }}</div>
              <div>第{{ scope.row.periodNo }}节</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="scheduleType" label="类型" width="80">
          <template #default="scope">
            <el-tag :type="getScheduleTypeTag(scope.row.scheduleType)">
              {{ scope.row.scheduleType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="80">
          <template #default="scope">
            <el-rate v-model="scope.row.priority" disabled show-score :max="5" />
          </template>
        </el-table-column>
        <el-table-column prop="isFixed" label="固定" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.isFixed ? 'success' : 'info'">
              {{ scope.row.isFixed ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="scheduleRemark" label="备注" width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="info" size="small" @click="handleViewDetail(scope.row)">详情</el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10,20,50,100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 智能排课对话框 -->
    <el-dialog v-model="intelligentDialogVisible" title="智能排课" width="800px">
      <el-form :model="intelligentForm" label-width="120px">
        <el-form-item label="学期" required>
          <el-select v-model="intelligentForm.semester" placeholder="请选择学期" style="width: 100%" @change="handleSemesterChange">
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2025秋季" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="排课模式" required>
          <el-radio-group v-model="intelligentForm.mode">
            <el-radio label="simple">简单模式（全自动）</el-radio>
            <el-radio label="advanced">高级模式（选择班级和课程）</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 高级模式选项 -->
        <div v-if="intelligentForm.mode === 'advanced'">
          <el-form-item label="选择班级" required>
            <el-select 
              v-model="intelligentForm.selectedClasses" 
              placeholder="请选择要排课的班级" 
              style="width: 100%" 
              multiple 
              @change="handleClassChange"
            >
              <el-option 
                v-for="clazz in clazzList" 
                :key="clazz.clazzId" 
                :label="clazz.clazzName" 
                :value="clazz.clazzId" 
              />
            </el-select>
          </el-form-item>

          <el-form-item label="班级课程" v-if="intelligentForm.selectedClasses.length > 0">
            <div class="class-course-selection">
              <div v-for="clazzId in intelligentForm.selectedClasses" :key="clazzId" class="class-course-item">
                <div class="class-name">
                  {{ getClazzName(clazzId) }}
                  <el-tag size="small" :type="getWeeklyLimitStatus(clazzId)">
                    周课时: {{ getWeeklyHours(clazzId) }}/20
                  </el-tag>
                </div>
                <el-checkbox-group v-model="intelligentForm.selectedCourses[clazzId]" @change="handleCourseSelectionChange">
                  <el-checkbox 
                    v-for="course in getClassCourses(clazzId)" 
                    :key="course.courseId" 
                    :label="course.courseId"
                    :disabled="!canSelectCourse(clazzId, course)"
                  >
                    {{ course.courseName }} ({{ course.credit }}学分 / 每周{{ getCourseHours(course) }}节)
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="约束条件">
            <el-checkbox-group v-model="intelligentForm.constraints">
              <el-checkbox label="teacher_conflict">避免教师时间冲突</el-checkbox>
              <el-checkbox label="classroom_conflict">避免教室时间冲突</el-checkbox>
              <el-checkbox label="student_conflict">避免学生课程冲突</el-checkbox>
              <el-checkbox label="weekly_limit">遵守周课时限制（≤20节）</el-checkbox>
              <el-checkbox label="teacher_preference">考虑教师时间偏好</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>

        <el-form-item label="排课说明">
          <el-input v-model="intelligentForm.description" type="textarea" :rows="3" placeholder="请输入排课说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="intelligentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleIntelligentSubmit" :loading="intelligentLoading">开始排课</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑排课对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" @close="handleDialogClose">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程" prop="courseId">
              <el-select v-model="form.courseId" placeholder="请选择课程" style="width: 100%" @change="handleCourseChange">
                <el-option 
                  v-for="course in courseList" 
                  :key="course.courseId" 
                  :label="course.courseName" 
                  :value="course.courseId" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教师" prop="teacherId">
              <el-select v-model="form.teacherId" placeholder="请选择教师" style="width: 100%">
                <el-option 
                  v-for="teacher in teacherList" 
                  :key="teacher.teacherId" 
                  :label="teacher.teacherName" 
                  :value="teacher.teacherId" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班级" prop="clazzId">
              <el-select v-model="form.clazzId" placeholder="请选择班级" style="width: 100%">
                <el-option 
                  v-for="clazz in clazzList" 
                  :key="clazz.clazzId" 
                  :label="clazz.clazzName" 
                  :value="clazz.clazzId" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教室" prop="classroomId">
              <el-select v-model="form.classroomId" placeholder="请选择教室" style="width: 100%">
                <el-option 
                  v-for="classroom in classroomList" 
                  :key="classroom.classroomId" 
                  :label="classroom.classroomName" 
                  :value="classroom.classroomId" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="学期" prop="semester">
              <el-select v-model="form.semester" placeholder="请选择学期" style="width: 200px">
                <el-option label="2024春季" value="2024春季" />
                <el-option label="2024秋季" value="2024秋季" />
                <el-option label="2025春季" value="2025春季" />
                <el-option label="2025秋季" value="2025秋季" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="周次" prop="weekNo">
              <el-input-number v-model="form.weekNo" :min="1" :max="20" placeholder="周次" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="星期" prop="dayOfWeek">
              <el-select v-model="form.dayOfWeek" placeholder="星期" style="width: 100%">
                <el-option label="星期一" :value="1" />
                <el-option label="星期二" :value="2" />
                <el-option label="星期三" :value="3" />
                <el-option label="星期四" :value="4" />
                <el-option label="星期五" :value="5" />
                <el-option label="星期六" :value="6" />
                <el-option label="星期日" :value="7" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="节次" prop="periodNo">
              <el-input-number v-model="form.periodNo" :min="1" :max="12" placeholder="节次" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="排课类型" prop="scheduleType">
              <el-select v-model="form.scheduleType" placeholder="请选择类型" style="width: 100%">
                <el-option label="正常" value="正常" />
                <el-option label="调课" value="调课" />
                <el-option label="补课" value="补课" />
                <el-option label="考试" value="考试" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="有效" value="ACTIVE" />
                <el-option label="取消" value="CANCELLED" />
                <el-option label="暂停" value="SUSPENDED" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优先级" prop="priority">
              <el-rate v-model="form.priority" :max="5" show-text />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="是否固定">
          <el-radio-group v-model="form.isFixed">
            <el-radio :label="1">固定</el-radio>
            <el-radio :label="0">可调整</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="scheduleRemark">
          <el-input v-model="form.scheduleRemark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="排课详情" width="600px">
      <div class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="课程名称">{{ detailData.courseName }}</el-descriptions-item>
          <el-descriptions-item label="教师">{{ detailData.teacherName }}</el-descriptions-item>
          <el-descriptions-item label="班级">{{ detailData.clazzName }}</el-descriptions-item>
          <el-descriptions-item label="教室">{{ detailData.classroomName }}</el-descriptions-item>
          <el-descriptions-item label="时间安排" :span="2">
            第{{ detailData.weekNo }}周 {{ getWeekDayName(detailData.dayOfWeek) }} 第{{ detailData.periodNo }}节
          </el-descriptions-item>
          <el-descriptions-item label="排课类型">{{ detailData.scheduleType }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ getStatusText(detailData.status) }}</el-descriptions-item>
          <el-descriptions-item label="优先级">{{ detailData.priority }}/5</el-descriptions-item>
          <el-descriptions-item label="是否固定">{{ detailData.isFixed ? '是' : '否' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{ formatDate(detailData.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间" :span="2">{{ formatDate(detailData.updateTime) }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ detailData.scheduleRemark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Delete, Star, Edit, Warning, Download, Reading, User, School } from '@element-plus/icons-vue'
import { 
  getScheduleList, 
  getSchedulePage,
  intelligentSchedule,
  executeAdvancedSchedule,
  getAdvancedClazzes,
  getAdvancedCourses,
  getAdvancedDefaultParams,
  validateAdvancedParams,
  addSchedule, 
  updateSchedule, 
  deleteSchedule,
  checkScheduleConflict 
} from '../api/schedule'
import { getCourseList } from '../api/course'
import { getTeacherList } from '../api/teacher'
import { getClazzList } from '../api/clazz'

const searchForm = reactive({
  semester: '',
  courseName: '',
  teacherName: '',
  clazzName: '',
  scheduleType: '',
  status: ''
})

const pagination = reactive({ currentPage: 1, pageSize: 10, total: 0 })
const scheduleList = ref([])
const loading = ref(false)
const selectedIds = ref([])

const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

const detailDialogVisible = ref(false)
const detailData = ref({})

const intelligentDialogVisible = ref(false)
const intelligentLoading = ref(false)
const intelligentForm = reactive({
  semester: '',
  mode: 'simple',
  selectedClasses: [],
  selectedCourses: {},
  constraints: ['teacher_conflict', 'classroom_conflict', 'student_conflict', 'weekly_limit'],
  description: ''
})

// 班级课程数据
const classCoursesData = ref({})
const classWeeklyHours = ref({})

// 基础数据
const courseList = ref([])
const teacherList = ref([])
const clazzList = ref([])
const classroomList = ref([])

const form = reactive({
  scheduleId: null,
  courseId: null,
  teacherId: null,
  classroomId: null,
  clazzId: null,
  timeSlotId: null,
  semester: '2024春季',
  weekNo: 1,
  dayOfWeek: 1,
  periodNo: 1,
  scheduleType: '正常',
  status: 'ACTIVE',
  priority: 3,
  isFixed: 0,
  scheduleRemark: ''
})

const rules = {
  courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
  teacherId: [{ required: true, message: '请选择教师', trigger: 'change' }],
  classroomId: [{ required: true, message: '请选择教室', trigger: 'change' }],
  clazzId: [{ required: true, message: '请选择班级', trigger: 'change' }],
  semester: [{ required: true, message: '请选择学期', trigger: 'change' }],
  weekNo: [{ required: true, message: '请输入周次', trigger: 'blur' }],
  dayOfWeek: [{ required: true, message: '请选择星期', trigger: 'change' }],
  periodNo: [{ required: true, message: '请输入节次', trigger: 'blur' }],
  scheduleType: [{ required: true, message: '请选择排课类型', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const formRef = ref()

// 工具函数
const getWeekDayName = (dayOfWeek) => {
  const days = ['', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
  return days[dayOfWeek] || ''
}

const getScheduleTypeTag = (type) => {
  const typeMap = {
    '正常': 'success',
    '调课': 'warning',
    '补课': 'info',
    '考试': 'danger'
  }
  return typeMap[type] || 'info'
}

const getStatusTag = (status) => {
  const statusMap = {
    'ACTIVE': 'success',
    'CANCELLED': 'danger',
    'SUSPENDED': 'warning'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'ACTIVE': '有效',
    'CANCELLED': '取消',
    'SUSPENDED': '暂停'
  }
  return statusMap[status] || status
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit', 
    hour: '2-digit', 
    minute: '2-digit', 
    second: '2-digit' 
  })
}

// 事件处理
const handleSearch = () => {
  console.log('🔍 执行搜索，当前搜索条件:', searchForm)
  pagination.currentPage = 1
  fetchScheduleList()
}

const handleReset = () => {
  console.log('🔄 重置搜索条件')
  Object.keys(searchForm).forEach(k => searchForm[k] = '')
  pagination.currentPage = 1
  fetchScheduleList()
}

const handleIntelligentSchedule = () => {
  intelligentDialogVisible.value = true
}

const handleIntelligentSubmit = async () => {
  if (!intelligentForm.semester) {
    ElMessage.warning('请选择学期')
    return
  }
  
  if (intelligentForm.mode === 'advanced') {
    if (intelligentForm.selectedClasses.length === 0) {
      ElMessage.warning('请选择要排课的班级')
      return
    }
    
    // 检查是否选择了课程
    let hasSelectedCourses = false
    for (const clazzId of intelligentForm.selectedClasses) {
      if (intelligentForm.selectedCourses[clazzId] && intelligentForm.selectedCourses[clazzId].length > 0) {
        hasSelectedCourses = true
        break
      }
    }
    
    if (!hasSelectedCourses) {
      ElMessage.warning('请为选择的班级选择要排课的课程')
      return
    }
    
    // 检查周课时限制（按每周节数校验）
    for (const clazzId of intelligentForm.selectedClasses) {
      const selectedCourses = intelligentForm.selectedCourses[clazzId] || []
      const totalHours = selectedCourses.reduce((sum, courseId) => {
        const course = getClassCourses(clazzId).find(c => c.courseId === courseId)
        return sum + getCourseHours(course)
      }, 0)

      if (totalHours > 20) {
        ElMessage.warning(`${getClazzName(clazzId)}的周课时超过20节限制`)
        return
      }
    }
  }
  
  intelligentLoading.value = true
  try {
    if (intelligentForm.mode === 'simple') {
      await intelligentSchedule(intelligentForm.semester)
    } else {
      // 调用后端高级智能排课接口
      await executeAdvancedSchedule({
        semester: intelligentForm.semester,
        selectedClazzIds: intelligentForm.selectedClasses,
        selectedCourseIds: Object.values(intelligentForm.selectedCourses).flat(),
        maxPeriodsPerWeek: 12,
        maxPeriodsPerDay: 8,
        evenDistribution: intelligentForm.constraints?.includes('even_distribution') ?? true,
        avoidTeacherConflict: intelligentForm.constraints?.includes('teacher_conflict') ?? true,
        avoidClassroomConflict: intelligentForm.constraints?.includes('classroom_conflict') ?? true,
        priority: 3,
        remark: intelligentForm.description
      })
    }
    ElMessage.success('智能排课成功')
    intelligentDialogVisible.value = false
    fetchScheduleList()
  } catch (error) {
    console.error('智能排课失败:', error)
  } finally {
    intelligentLoading.value = false
  }
}

const handleAdd = () => {
  dialogTitle.value = '手动排课'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑排课'
  isEdit.value = true
  Object.keys(form).forEach(k => form[k] = row[k] ?? '')
  dialogVisible.value = true
}

const handleViewDetail = (row) => {
  detailData.value = { ...row }
  detailDialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除排课 "${row.courseName}" 吗？`, '删除确认', { 
    confirmButtonText: '确定', 
    cancelButtonText: '取消', 
    type: 'warning' 
  })
    .then(async () => {
      await deleteSchedule(row.scheduleId)
      ElMessage.success('删除成功')
      fetchScheduleList()
    })
    .catch(() => ElMessage.info('已取消删除'))
}

const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.scheduleId)
}

const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的排课')
    return
  }
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 个排课吗？`, '批量删除确认', { 
    confirmButtonText: '确定', 
    cancelButtonText: '取消', 
    type: 'warning' 
  })
    .then(async () => {
      // 这里应该调用批量删除API
      for (const id of selectedIds.value) {
        await deleteSchedule(id)
      }
      ElMessage.success('批量删除成功')
      selectedIds.value = []
      fetchScheduleList()
    })
    .catch(() => ElMessage.info('已取消删除'))
}

const handleBatchAdjust = () => {
  ElMessage.info('批量调整功能开发中...')
}

const handleConflictCheck = async () => {
  try {
    // 这里应该调用冲突检查API
    ElMessage.success('冲突检查完成，未发现冲突')
  } catch (error) {
    ElMessage.error('冲突检查失败')
  }
}

const handleExportSchedule = () => {
  try {
    if (scheduleList.value.length === 0) {
      ElMessage.warning('暂无数据可导出')
      return
    }
    
    // 准备CSV内容
    let csvContent = '\uFEFF' // UTF-8 BOM
    
    // 表头
    csvContent += '课程名称,教师姓名,班级,教室,周次,星期,节次,类型,状态,优先级,备注\n'
    
    // 数据行
    scheduleList.value.forEach(item => {
      csvContent += `"${item.courseName || ''}",`
      csvContent += `"${item.teacherName || ''}",`
      csvContent += `"${item.clazzName || ''}",`
      csvContent += `"${item.classroomName || ''}",`
      csvContent += `"第${item.weekNo || ''}周",`
      csvContent += `"${getWeekDayName(item.dayOfWeek)}",`
      csvContent += `"第${item.periodNo || ''}节",`
      csvContent += `"${item.scheduleType || ''}",`
      csvContent += `"${getStatusText(item.status)}",`
      csvContent += `"${item.priority || 0}",`
      csvContent += `"${item.scheduleRemark || ''}"\n`
    })
    
    // 创建Blob并下载
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `排课数据_${new Date().toLocaleDateString()}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

const handleSubmit = async () => {
  const valid = await formRef.value.validate()
  if (!valid) return
  
  try {
    // 检查冲突
    const conflictResult = await checkScheduleConflict(form)
    if (conflictResult.data) {
      ElMessage.warning('存在时间冲突，请调整时间安排')
      return
    }
    
    if (isEdit.value) {
      await updateSchedule(form)
      ElMessage.success('编辑成功')
    } else {
      await addSchedule(form)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    fetchScheduleList()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

const handleDialogClose = () => {
  resetForm()
  formRef.value?.resetFields()
}

const resetForm = () => {
  Object.keys(form).forEach(k => {
    if (k === 'scheduleId') form[k] = null
    else if (k === 'weekNo') form[k] = 1
    else if (k === 'dayOfWeek') form[k] = 1
    else if (k === 'periodNo') form[k] = 1
    else if (k === 'scheduleType') form[k] = '正常'
    else if (k === 'status') form[k] = 'ACTIVE'
    else if (k === 'priority') form[k] = 3
    else if (k === 'isFixed') form[k] = 0
    else form[k] = ''
  })
}

const handleCourseChange = (courseId) => {
  // 课程改变时，可以自动填充相关信息
  const course = courseList.value.find(c => c.courseId === courseId)
  if (course) {
    // 可以根据课程信息自动设置其他字段
  }
}

// 辅助函数：获取名称
const getTeacherName = (teacherId) => {
  const teacher = teacherList.value.find(t => t.teacherId === teacherId)
  return teacher ? teacher.teacherName : '未知教师'
}

const getCourseName = (courseId) => {
  const course = courseList.value.find(c => c.courseId === courseId)
  return course ? course.courseName : '未知课程'
}

const getClassroomName = (classroomId) => {
  const classroom = classroomList.value.find(c => c.classroomId === classroomId)
  return classroom ? classroom.classroomName : '未知教室'
}

// 智能排课相关方法
const handleSemesterChange = () => {
  // 学期改变时，清空班级和课程选择
  intelligentForm.selectedClasses = []
  intelligentForm.selectedCourses = {}
  intelligentForm.fixedSchedules = [] // 清空固定排课
  classCoursesData.value = {}
  classWeeklyHours.value = {}
}

const handleClassChange = async () => {
  // 班级改变时，按班级院系(dept)获取可选课程
  for (const clazzId of intelligentForm.selectedClasses) {
    if (!classCoursesData.value[clazzId]) {
      try {
        const clazz = clazzList.value.find(c => c.clazzId === clazzId)
        
        // 🔥 判断是否为选修班（班级名包含"选修"）
        const isElectiveClass = clazz && clazz.clazzName && clazz.clazzName.includes('选修')
        
        let records = []
        
        if (isElectiveClass) {
          // 🔥 选修班：只显示对应的选修课
          // 从班级名中提取课程名，如 "linux-选修班" → "linux"
          const courseName = clazz.clazzName.replace(/-?选修班?$/, '').trim()
          console.log(`📚 选修班 [${clazz.clazzName}] 提取课程名: ${courseName}`)
          
          // 查询所有课程，然后筛选匹配的选修课
          const response = await getCourseList({ pageNum: 1, pageSize: 1000 })
          const allRecords = response?.data?.records || response?.data || []
          records = allRecords.filter(course => 
            course.courseType === '选修' && 
            course.courseName && 
            course.courseName.toLowerCase().includes(courseName.toLowerCase())
          )
          
          console.log(`✅ 选修班 [${clazz.clazzName}] 匹配到 ${records.length} 门选修课`)
        } else {
          // 🔥 普通班级：按院系查询必修课程（排除选修课）
          const dept = clazz ? clazz.dept : ''
          const response = await getCourseList({ pageNum: 1, pageSize: 1000, dept })
          const allRecords = response?.data?.records || response?.data || []
          // 过滤出必修课程，排除选修课
          records = allRecords.filter(course => 
            course.courseType !== '选修'
          )
          
          console.log(`✅ 必修班 [${clazz.clazzName}] 查询到 ${records.length} 门必修课（已排除选修课）`)
        }
        
        classCoursesData.value[clazzId] = Array.isArray(records) ? records : []
        // 初始化本周已选课时（按选择动态计算）
        classWeeklyHours.value[clazzId] = 0
        // 确保选择数组存在，避免 v-model 绑定为空导致无法选择
        if (!Array.isArray(intelligentForm.selectedCourses[clazzId])) {
          intelligentForm.selectedCourses[clazzId] = []
        }
      } catch (error) {
        console.warn(`获取班级${clazzId}课程信息失败:`, error)
        classCoursesData.value[clazzId] = []
        classWeeklyHours.value[clazzId] = 0
        if (!Array.isArray(intelligentForm.selectedCourses[clazzId])) {
          intelligentForm.selectedCourses[clazzId] = []
        }
      }
    }
  }

  // 移除未选择的班级数据
  for (const clazzId in classCoursesData.value) {
    if (!intelligentForm.selectedClasses.includes(parseInt(clazzId))) {
      delete classCoursesData.value[clazzId]
      delete classWeeklyHours.value[clazzId]
      delete intelligentForm.selectedCourses[clazzId]
    }
  }
}

const handleCourseSelectionChange = () => {
  // 课程选择改变时，更新周课时统计
  for (const clazzId of intelligentForm.selectedClasses) {
    const selectedCourses = intelligentForm.selectedCourses[clazzId] || []
    const totalHours = selectedCourses.reduce((sum, courseId) => {
      const course = getClassCourses(clazzId).find(c => c.courseId === courseId)
      return sum + getCourseHours(course)
    }, 0)
    
    classWeeklyHours.value[clazzId] = totalHours
  }
}

const getClazzName = (clazzId) => {
  const clazz = clazzList.value.find(c => c.clazzId === clazzId)
  return clazz ? clazz.clazzName : `班级${clazzId}`
}

const getClassCourses = (clazzId) => {
  return classCoursesData.value[clazzId] || []
}

const getWeeklyHours = (clazzId) => {
  return classWeeklyHours.value[clazzId] || 0
}

const getWeeklyLimitStatus = (clazzId) => {
  const hours = getWeeklyHours(clazzId)
  if (hours > 20) return 'danger'
  if (hours > 16) return 'warning'
  return 'success'
}

const canSelectCourse = (clazzId, course) => {
  const currentHours = getWeeklyHours(clazzId)
  const selectedCourses = intelligentForm.selectedCourses[clazzId] || []
  const isSelected = selectedCourses.includes(course.courseId)
  
  if (isSelected) return true
  
  // 检查选择后是否会超过20节限制
  return (currentHours + getCourseHours(course)) <= 20
}

// 兼容后端不同字段，获取课程每周课时（节/周）
const getCourseHours = (course) => {
  if (!course) return 0
  // 固定返回每周2节
  return 2
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchScheduleList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchScheduleList()
}

// 数据获取
const fetchScheduleList = async () => {
  loading.value = true
  try {
    // 使用后端分页接口，避免前端自身分页导致两页相同
    // 添加搜索条件参数
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm // 将搜索表单的所有参数传递给后端
    }
    
    console.log('查询排课列表，参数:', params)
    const response = await getSchedulePage(params)
    const data = response?.data || {}
    scheduleList.value = data.records || []
    pagination.total = data.total || 0
    
    console.log('查询结果:', scheduleList.value.length, '条记录，共', pagination.total, '条')
  } catch (error) {
    console.warn('获取排课列表失败，使用模拟数据:', error)
    // 使用模拟数据
    scheduleList.value = [
      {
        scheduleId: 1,
        courseName: '数据结构',
        teacherName: '张老师',
        clazzName: '计算机1班',
        classroomName: 'A101',
        weekNo: 1,
        dayOfWeek: 1,
        periodNo: 1,
        scheduleType: '正常',
        status: 'ACTIVE',
        priority: 3,
        isFixed: 0,
        scheduleRemark: '正常上课'
      }
    ]
    pagination.total = 1
  } finally {
    loading.value = false
  }
}

const fetchBaseData = async () => {
  try {
    const [courseRes, teacherRes, clazzRes] = await Promise.all([
      getCourseList({ pageNum: 1, pageSize: 1000 }),
      getTeacherList({ pageNum: 1, pageSize: 1000 }),
      getClazzList({ pageNum: 1, pageSize: 1000 })
    ])
    
    courseList.value = courseRes.data?.records || []
    teacherList.value = teacherRes.data?.records || []
    clazzList.value = clazzRes.data?.records || []
    
    // 模拟教室数据
    classroomList.value = [
      { classroomId: 1, classroomName: 'A101' },
      { classroomId: 2, classroomName: 'A102' },
      { classroomId: 3, classroomName: 'B201' },
      { classroomId: 4, classroomName: 'B202' }
    ]
  } catch (error) {
    console.warn('获取基础数据失败:', error)
  }
}

onMounted(() => {
  fetchScheduleList()
  fetchBaseData()
})
</script>

<style scoped>
.schedule-management {
  background: #f5f7fa;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
  letter-spacing: 1px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  border: none;
  background: #ffffff;
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.12);
}

.search-card :deep(.el-card__body) {
  padding: 20px 24px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 16px;
}

.search-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  font-size: 14px;
  padding-right: 8px;
}

.search-form :deep(.el-input__wrapper) {
  border-radius: 6px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: all 0.3s ease;
}

.search-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

.search-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset !important;
}

.search-form :deep(.el-select .el-input__wrapper) {
  border-radius: 6px;
}

.search-form :deep(.el-input__prefix) {
  color: #909399;
}

.search-form :deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
}

.action-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
}

.action-card :deep(.el-card__body) {
  padding: 16px 20px;
}

.action-buttons {
  display: flex;
  justify-content: flex-start;
  gap: 12px;
  flex-wrap: wrap;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
  overflow: hidden;
}

.table-card :deep(.el-card__body) {
  padding: 0;
}

.time-info {
  font-size: 12px;
  line-height: 1.4;
}

.pagination-container {
  margin-top: 16px;
  padding: 16px 20px;
  display: flex;
  justify-content: center;
  background: #f5f7fa;
  border-top: 1px solid #ebeef5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
}

.detail-content {
  padding: 20px 0;
}

.detail-content :deep(.el-descriptions__header) {
  background: #f5f7fa;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

/* 智能排课对话框样式 */
.class-course-selection {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px;
  background: #fafafa;
}

.class-course-item {
  margin-bottom: 20px;
  padding: 16px;
  background: #ffffff;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.class-course-item:last-child {
  margin-bottom: 0;
}

.class-name {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
  font-weight: 600;
  color: #2c3e50;
  font-size: 16px;
}

.class-course-item :deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.class-course-item :deep(.el-checkbox) {
  margin-right: 0;
  margin-bottom: 8px;
}

.class-course-item :deep(.el-checkbox__label) {
  font-size: 14px;
  color: #606266;
}

.class-course-item :deep(.el-checkbox.is-disabled .el-checkbox__label) {
  color: #c0c4cc;
}

/* 固定排课样式 */
.fixed-schedule-section {
  margin-top: 10px;
}

.fixed-schedule-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.section-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.section-tip .el-icon {
  color: #409eff;
}

.fixed-schedule-list {
  margin-top: 16px;
}

.time-info {
  line-height: 1.6;
  font-size: 13px;
}

.time-info div {
  margin: 2px 0;
}
</style>
